// cocos调试时，无法通过文件系统获得配置，所以通过打包的方式，在调试模式下进行模拟

package create_debug_config

import (
	"encoding/json"
	"fmt"
	"os"
	"path/filepath"
	"strings"
	"wails/cmds/maketools"

	"gitee.com/zhongguo168a/gocodes/datax"
	"gitee.com/zhongguo168a/gocodes/datax/cachex/execlutil"
	"gitee.com/zhongguo168a/gocodes/gox/osx/filex"
	"gitee.com/zhongguo168a/gocodes/myx/logx"
	"github.com/codeskyblue/go-sh"
	"github.com/spf13/cobra"
)

var gamePath = "/mnt/d/projects/yxeditor/codes/G25.1"

func init() {
	startCmd := &cobra.Command{
		Use:   "execl-to-json",
		Short: "",
		Run: func(cmd *cobra.Command, args []string) {
			files := filex.NewFilter().
				IncludeSuffix(".xlsx").
				IgnoreDir(gamePath + "/配置表/卡片").
				GetFileInfosByPath(gamePath + "/配置表")
			for _, info := range files {
				if info.Path() == "." {
					continue
				}
				if string(info.Name()[0]) == "~" {
					continue
				}
				arr := strings.Split(filepath.Base(info.Name()), ".")
				execlToJson(info.Path(), arr[0])
			}
			execlToJsonCombine(gamePath+"/配置表/卡片/单位表.xlsx", "单位表")
			execlToJsonCombine(gamePath+"/配置表/卡片/技能表.xlsx", "技能表")
			execlToJsonCombine(gamePath+"/配置表/卡片/物品表.xlsx", "物品表")
			execlToJsonSave(gamePath + "/publish/values.json")
			rsync()
		},
	}

	maketools.RootCmd.AddCommand(startCmd)
}

var result = datax.M{}

func execlToJsonCombine(loadPath string, name string) {
	{
		m := execlutil.ExeclToTable(loadPath)
		a := func() (x datax.A) {
			func() {
				count := 0
				for _, isheet := range m {
					sheet := isheet.(datax.A)
					for _, val := range sheet {
						x = append(x, val)
						count++
						if count >= 2 {
							return
						}
					}
				}
			}()

			for _, isheet := range m {
				sheet := isheet.(datax.A)
				count := 0
				for _, val := range sheet {
					count++
					if count <= 2 {
						continue
					}
					x = append(x, val)
				}
			}
			return
		}()
		result[name] = func() (x datax.M) {
			x = datax.M{}
			x["合并"] = a
			return
		}()
	}
}

func execlToJson(loadPath string, name string) {
	fmt.Println("load", loadPath, name)
	{
		m := execlutil.ExeclToTable(loadPath)
		result[name] = m
	}
}

func execlToJsonSave(publishPath string) {
	{
		b, _ := json.MarshalIndent(result, "", "\t")
		err := os.WriteFile(publishPath, b, os.ModePerm)
		if err != nil {
			fmt.Println("write file", err)
			return
		}
	}
}

var sourcePath = gamePath + "/publish"

func rsync() {
	cmd := sh.NewSession()
	cmd.ShowCMD = true
	//clientPath + "/assets/resources/project/debug_config.json"
	var err error
	{
		err = cmd.Command("/bin/sh", "-c",
			fmt.Sprintf(`rsync -avr %v %v`,
				sourcePath+"/values.json",
				gamePath+"/client-cocos/assets/resources/project",
			)).Run()
		if err != nil {
			logx.Error(err)
		}
	}
}
